import React, { useState } from "react";
import { Modal, Input, Space, Button, message, Segmented } from "antd";
import { PlusOutlined, MinusCircleOutlined, AimOutlined, HomeOutlined, UserOutlined } from "@ant-design/icons";
import { invoke } from "@tauri-apps/api/core";
import { useLoading } from "../../components/LoadingProvider";

const typeOptions = ["tcp", "udp", "http", "https", "tcpmux"];
const generateRandomName = () => `service-${Math.floor(Math.random() * 10000)}`;
const AddProxieModal: React.FC<{
  visible: boolean;
  onCancel: () => void;
  onSuccess: () => void;
}> = ({ visible, onCancel, onSuccess }) => {
  const [newService, setNewService] = useState<any>({
    proxy_type: "http",          // 默认 http
    name: generateRandomName(),
    custom_domains: [""],
    local_ip: "127.0.0.1",
    local_port: 8080,
    remote_port: 0,             // tcp/udp
    multiplexer: "httpconnect", // tcpmux 默认
    routeByHTTPUser: "",        // tcpmux 可选
  });
  const { showLoading, hideLoading } = useLoading();

  const validate = () => {
    if (!newService.name?.trim()) {
      message.error("别名不能为空");
      return false;
    }
    if (!newService.local_ip?.trim()) {
      message.error("Host 不能为空");
      return false;
    }
    const port = Number(newService.local_port);
    if (!port || port < 1 || port > 65535) {
      message.error("端口必须是 1-65535");
      return false;
    }

    if ((newService.proxy_type === "tcp" || newService.proxy_type === "udp") &&
        (!newService.remote_port || newService.remote_port < 0 || newService.remote_port > 65535)) {
      message.error("远程端口必须是 0-65535");
      return false;
    }

    if ((newService.proxy_type === "http" || newService.proxy_type === "https" || newService.proxy_type === "tcpmux") &&
        (!newService.custom_domains || newService.custom_domains.length === 0)) {
      message.error("请至少添加一个域名");
      return false;
    }

    return true;
  };

  const handleSave = async () => {
    if (!validate()) return;
    showLoading()
    let payload: any = { ...newService };

    // 根据 proxy_type 保留特有字段
    switch (newService.proxy_type) {
      case "tcp":
      case "udp":
        payload.remote_port = Number(newService.remote_port) || 0;
        delete payload.multiplexer;
        delete payload.routeByHTTPUser;
        break;
      case "http":
      case "https":
        payload.custom_domains = newService.custom_domains.filter((d: string) => d.trim() !== "");
        delete payload.remote_port;
        delete payload.multiplexer;
        delete payload.routeByHTTPUser;
        break;
      case "tcpmux":
        payload.multiplexer = newService.multiplexer || "httpconnect";
        payload.custom_domains = newService.custom_domains.filter((d: string) => d.trim() !== "");
        payload.routeByHTTPUser = newService.routeByHTTPUser || "";
        delete payload.remote_port;
        break;
    }

    let result: any = await invoke("add_proxie", { proxy: payload });
    if (result.code) {
      message.success(result.msg);
      onCancel();
      onSuccess();
    } else {
      message.error(result.msg);
    }
    hideLoading()
  };

  const handleAddDomain = () =>
    setNewService({
      ...newService,
      custom_domains: [...(newService.custom_domains || []), ""],
    });

  const handleDomainChange = (idx: number, val: string) => {
    const newDomains = [...(newService.custom_domains || [])];
    newDomains[idx] = val;
    setNewService({ ...newService, custom_domains: newDomains });
  };

  const handleRemoveDomain = (idx: number) => {
    const newDomains = [...(newService.custom_domains || [])].filter((_, i) => i !== idx);
    setNewService({ ...newService, custom_domains: newDomains });
  };

  return (
    <Modal
      title="新增服务"
      visible={visible}
      onOk={handleSave}
      onCancel={onCancel}
      okText="保存"
      cancelText="取消"
    >
      <Space direction="vertical" style={{ width: "100%" }}>
        <Input
          addonBefore="ID"
          placeholder="系统生成"
          disabled
        />
        {/* 类型选择放最上面 */}
        <Segmented
          options={typeOptions.map(p => ({ label: p.toUpperCase(), value: p }))}
          value={newService.proxy_type} // 小写匹配默认值
          onChange={(val) =>
            setNewService({
              ...newService,
              proxy_type: val as string,
            })
          }
        />

        <Input
          addonBefore={
            <>
              <UserOutlined style={{ color: "#1890ff" }} />
            </>
          }
          placeholder="请输入别名"
          value={newService.name}
          onChange={(e) => setNewService({ ...newService, name: e.target.value })}
        />
        <Input
          addonBefore={
            <>
              <HomeOutlined style={{ color: "#52c41a" }} />
            </>
          }
          placeholder="请输入本地IP"
          value={newService.local_ip}
          onChange={(e) =>
            setNewService({ ...newService, local_ip: e.target.value })
          }
        />
      
        <Input
          addonBefore={
            <>
              <AimOutlined style={{ color: "#1890ff" }} />
            </>
          }
          placeholder="请输入本地端口"
          type="number"
          value={newService.local_port}
          onChange={(e) =>
            setNewService({ ...newService, local_port: Number(e.target.value) })
          }
        />

        {/* TCP/UDP 特有 remotePort */}
        {(newService.proxy_type === "tcp" || newService.proxy_type === "udp") && (
          <Input
            addonBefore="远程端口"
            type="number"
            value={newService.remote_port}
            onChange={(e) =>
              setNewService({ ...newService, remote_port: Number(e.target.value) })
            }
          />
        )}

        {/* TCMPUX 特有 multiplexer + routeByHTTPUser */}
        {newService.proxy_type === "tcpmux" && (
          <>
            <Input
              addonBefore="Multiplexer"
              value={newService.multiplexer}
              onChange={(e) =>
                setNewService({ ...newService, multiplexer: e.target.value })
              }
              disabled={true}
            />
            <Input
              addonBefore="RouteByHTTPUser"
              value={newService.routeByHTTPUser}
              placeholder="user"
              onChange={(e) =>
                setNewService({ ...newService, routeByHTTPUser: e.target.value })
              }
            />
          </>
        )}

        {/* HTTP/HTTPS/TCMPUX 特有域名 */}
        {(newService.proxy_type === "http" ||
          newService.proxy_type === "https" ||
          newService.proxy_type === "tcpmux") &&
          newService.custom_domains.map((domain: string, idx: number) => (
            <Space key={idx} style={{ width: "100%" }}>
              <Input
                value={domain}
                placeholder="http://*.frp.koalaboys.cn"
                onChange={(e) => handleDomainChange(idx, e.target.value)}
              />
              <MinusCircleOutlined
                onClick={() => handleRemoveDomain(idx)}
                style={{ color: "red" }}
              />
            </Space>
          ))}

        {(newService.proxy_type === "http" ||
          newService.proxy_type === "https" ||
          newService.proxy_type === "tcpmux") && (
          <Button
            type="dashed"
            block
            icon={<PlusOutlined />}
            onClick={handleAddDomain}
          >
            添加域名
          </Button>
        )}
      </Space>
    </Modal>
  );
};

export default AddProxieModal;
